package com.example.demo.config;

import com.example.demo.util.ConstVariable;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashSet;

/**
 * 用户登录拦截器（查看当前用户是否登录）
 */
@Component
public class LoginInterception implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(ConstVariable.USER_SESSION_KEY) == null) {
            // 当前用户未登录，进行拦截--->跳转到登录页面--->后端我们只用给前端返回状态和数据，我们后端不用管页面怎么，跳转工作是前端的事情

            response.setStatus(401);
            response.sendError(401, "当前用户为登录，没有权限访问该接口");
            return false;
        }
        return true;
    }
}
